package com.abc.robot01.activity

import android.os.Bundle
import android.os.RemoteException
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.navigation.ui.AppBarConfiguration
import com.abc.robot01.R
import com.abc.robot01.RobotOSApplication
import com.abc.robot01.activity.BaseActivity.Companion
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.FetchDataRequest456
import com.abc.robot01.room.DatabaseContext
import com.abc.robot01.vivemodel.BaseViewModel
import com.abc.robot01.vivemodel.Robot
import com.ainirobot.coreservice.client.StatusListener
import com.ainirobot.coreservice.client.listener.TextListener
import com.ainirobot.coreservice.client.speech.SkillApi
import com.ainirobot.coreservice.client.speech.SkillCallback
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 */
open class BaseVoiceActivity : AppCompatActivity() {
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var mSkillApi: SkillApi

    open suspend fun pollNotce(viewModel2: BaseViewModel){
        while (1==1){
            delay(5000);//杨 要求5秒
            try {
                val res = RetrofitService.instance.getNoticeList(
                    accessToken = Robot.accessToken,
                    companyId = Robot.companyId,
                    userId = Robot.userId,
                    request = FetchDataRequest456(
                        fetchSize = 1,
                        childTypes = listOf("RENDER"),
                    )
                )
                if (res.data.list.isEmpty()) {
                    Log.e(BaseActivity.TAG, "没有新的通知:${res}")
                    continue
                }
                Log.e(BaseActivity.TAG, "有新的通知:${res}")
                val a = res.data.list.component1()
                if (a.showStatus == "Y") {
                    Log.e(TAG, "已读:${res}")
                    continue
                }
                Log.e(BaseActivity.TAG, "id:${a.id}")
                val id = a.dataId
                Log.e(BaseActivity.TAG, "通知:${res.data.list.size}")
                val res2 = RetrofitService.instance.getRenderTaskInfo(
                    accessToken = Robot.accessToken,
                    companyId = Robot.companyId,
                    userId = Robot.userId,
                    id = id,
                )
                Log.e(BaseActivity.TAG, "渲染:${res2}")

                viewModel2.noticeName.value = res2.data.name
                viewModel2.noticeTime.value = res2.data.endTime
                viewModel2.dataId9.value = a.dataId
                viewModel2.thumbnail9.value = res2.data.thumbnail
                viewModel2.pageUrl9.value = a.pageUrl

                viewModel2.isDialogVisible.value = true
                delay(3_000);
                val s = RetrofitService.instance.setRead(
                    accessToken = Robot.accessToken,
                    companyId = Robot.companyId,
                    userId = Robot.userId,
                    id = a.id,
                ).string()
                Log.e(BaseActivity.TAG, "${s}")
                viewModel2.isDialogVisible.value = false
            }
            catch (e:Exception){
//                 throw   RuntimeException("1")
            }
        }
    }



    open fun  handleVoiceCommand(asr:String): Boolean{
         return false
    }

    val statusListener = object : StatusListener() {
        @Throws(RemoteException::class)
        override fun onStatusUpdate(type: String, data: String) {
            // Implement your logic here
        }
    }

    private val skillCallback = object : com.abc.robot01.AsrCallback {
        override fun onQueryAsrResult(asrResult: String) {
            Log.e(TAG, "onQueryAsrResult:" + asrResult);
            if (handleVoiceCommand(asrResult)) {
                return
            }
//            if(asrResult=="你好"){
//                playTTS("近日，在科技界引起广泛关注的事件是苹果公司最新发布的iPhone 15系列。这款新机型不仅延续了苹果一贯的高端设计，还在性能、摄像功能以及环保材质的使用上进行了多项升级")
//                return
//            }
            lifecycleScope.launch(IO) {
            getAnswer(asrResult)?.let {
                playTTS(it)
            }
        }
        }
    }

     suspend fun  getAnswer(question:String):String?{
         Log.e(TAG, "查询问题：$question");
        val questions = DatabaseContext.getChatQuestionDao().queryCmd(question) ?: return null
        Log.e(TAG, "Ok，存在：$question");
          return DatabaseContext.getChatAnswerDao().queryAnswerByCmdId(questions.cmd_id)[0].ttsText
        }

    open fun playTTS(text: String) {
        Log.e(TAG, "开始播放：$text");
        RobotOSApplication.getInstance().skillApi?.playText(text,object : TextListener() {
            override fun onStart() {
                Log.e(TAG, "playText onStart");
                // 播放开始
//                lifecycleScope.launch(Dispatchers.Main){
//                }
            }

            override fun onStop() {
                Log.e(TAG, "playText onStop");
                // 播放停止
//                lifecycleScope.launch(Dispatchers.Main){
//                }
            }

            override fun onError() {
                Log.e(TAG, "playText onError");
                // 播放错误
            }

            override fun onComplete() {
                Log.e(TAG, "playText onComplete");
                // 播放完成
            }
        } )

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate");
    }

    override fun onResume() {
        super.onResume()
        if(RobotOSApplication.ROBOT){
        RobotOSApplication.getInstance().registerCallBack(skillCallback)
        }
    }

    override fun onPause() {
        super.onPause()
        if(RobotOSApplication.ROBOT){
        RobotOSApplication.getInstance().unregisterCallBack()
        }
    }

    fun replaceFragment(fragment: Fragment, tag: String) {
        val fragmentManager: FragmentManager = supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragment_container, fragment, tag)
        fragmentTransaction.addToBackStack(tag)
        fragmentTransaction.commit()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    companion object {
        val TAG = "BaseVoiceActivity"
    }
}
